<?php

class weixin
{
	public function valid()
    {
        $echoStr = $_GET["echostr"];

        //valid signature , option
        if($this->checkSignature()){
        	echo $echoStr;
        	exit;
        }
    }
    
    function get_open_id(){
        if($open_id=filter::get_user_input("open_id")){
            return array($open_id,"","");
        }
        else{
            include_once 'access_token.class.php';
            $token=new access_token();
            $access_token=$token->get_token();
            $url="https://api.weixin.qq.com/sns/oauth2/access_token?appid=".WEIXIN_APPID."&secret=".WEIXIN_APPSECRET."&code=".filter::get_user_input("code")."&grant_type=authorization_code";
            $ch = curl_init($url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_POST, 0);
            $data = curl_exec($ch);
            $data=json_decode($data,true);


            if(!isset($data['openid'])){
                if(filter::get_user_input("regetcode")){
                    log::write("weixin_error", var_export($data,1));
                    throw new Exception("获取微信openid失败1");
                }
                else{
                    $get_list=$_GET;
                    if(isset($get_list['code'])){
                        unset($get_list['code']);
                    }
                    $str='';
                    if(is_array($get_list)){
                        foreach( $get_list as $key=>$value){
                            $str.="&".$key."=".urlencode($value);
                        }
                    }
                    $str.="&regetcode=1";
                    header("Location:".wxJumper::get_url_weixin_auth2($str));
                    exit;
                }
            }
            $return=array($data['openid'],$data['access_token'],$data['refresh_token']);
            if(isset($data['unionid'])){
                $return[]=$data['unionid'];
            }else{
                $return[]=0;
            }
            return $return;
        }
    }
    
    function send_c_text_msg($open_id,$content){
        include_once 'access_token.class.php';
        $token=new access_token();
        $access_token=$token->get_token();
    
        $url="https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=$access_token";
    
        $data='
            {
                "touser":"'.$open_id.'",
                 "msgtype":"text",
                    "text":
                    {
                     "content":"'.$content.'"
                    }
            }
           ';
    
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        $data = curl_exec($ch);
        $data=json_decode($data,true);
       
        if($data['errcode']!=0){
            throw new Exception("提醒消息发送失败");
        }
    }
    
    function send_msg($content){
        include_once 'access_token.class.php';
        $token=new access_token();
        $access_token=$token->get_token();
        $url="https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=$access_token";
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $content);
        $data = curl_exec($ch);
        $data=json_decode($data,true);
        if($data['errcode']!=0){
            throw new Exception("下发信息不成功：".$data['errmsg']);
        }
    }
    
    function get_userinfo($open_id,$access_token,$refresh_token){
//         include_once 'access_token.class.php';
//         $token=new access_token();
//         $access_token=$token->get_token();
//         $url="https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=".APPID."&grant_type=refresh_token&refresh_token=".$refresh_token;
//         $ch = curl_init($url);
//         curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//         curl_setopt($ch, CURLOPT_POST, 0);
//         $data = curl_exec($ch);
//         $data=json_decode($data,true);
//         $access_token=$data['access_token'];
//         curl_close($ch);
//         exit;
        
        $url="https://api.weixin.qq.com/sns/userinfo?access_token=".$access_token."&openid=".$open_id."&lang=zh_CN";
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 0);
        $data = curl_exec($ch);
        $data=json_decode($data,true);

        return ($data);
    }
    
    private function createNonceStr($length = 16) {
        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        $str = "";
        for ($i = 0; $i < $length; $i++) {
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $str;
    }
    
    function get_js_auth($r_str=0){
        include_once 'access_token.class.php';
        $token=new access_token();
        $js_token=$token->get_js_token();
        $nonceStr=$this->createNonceStr();
        $t=time();
        if($r_str){
            $url=$r_str;
        }
        else{
            $url='http://'.$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'].'?'.$_SERVER['QUERY_STRING'];
        }
        $str="jsapi_ticket=".$js_token."&noncestr=".$nonceStr."&timestamp=".$t."&url=".$url;
        $sign=sha1($str);
        return array($t,$nonceStr,$sign,$str);
    }
    
    public function get_unionid($open_id){
        include_once 'access_token.class.php';
        $token=new access_token();
        $access_token=$token->get_token();
        $url="https://api.weixin.qq.com/cgi-bin/user/info?access_token=".$access_token."&openid=".$open_id."&lang=zh_CN";
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 0);
        $data = curl_exec($ch);
        $data=json_decode($data,true);
        if(isset($data['unionid']) && !empty($data['unionid'])){
            return ($data['unionid']);
        }
    }
    
    public function get_msg_attr($id,$mid){
        include_once 'access_token.class.php';
        $token=new access_token();
        $access_token=$token->get_token();
        $url="http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=".$access_token."&media_id=".$mid;
        file_put_contents(BASE_PATH."/public/img/msg_attr/$id.attr", file_get_contents($url));
        $this->amr2mp3(BASE_PATH."/public/img/msg_attr/$id.attr");
    }
    
  
    public function responseMsg()
    
    {
		$postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
// 		if (!empty($postStr) || 1){
            
//             $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
//             log::write("msg_recive", var_export($postObj,true));
//             $fromUsername = isset($postObj->FromUserName)?$postObj->FromUserName:"ojGVauBYvjsQCT4cewm4tPvufVbY";
//             $toUsername = isset($postObj->ToUserName)?$postObj->ToUserName:"gh_8efa7ace7bde";
//             $keyword = isset($postObj->Content)?(trim($postObj->Content)):"我要吃石榴";
//             $mt=isset($postObj->MsgType)?$postObj->MsgType:"text";
//             $event=isset($postObj->Event)?$postObj->Event:"";
		if (!empty($postStr)){
		
		    $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
// 		    log::write("msg_recive", var_export($postObj,true));
		    $fromUsername = isset($postObj->FromUserName)?$postObj->FromUserName:"";
		    $toUsername = isset($postObj->ToUserName)?$postObj->ToUserName:"";
		    $keyword = isset($postObj->Content)?(trim($postObj->Content)):"";
		    $mt=isset($postObj->MsgType)?$postObj->MsgType:"";
		    $event=isset($postObj->Event)?$postObj->Event:"";
		    $eventkey=isset($postObj->EventKey)?$postObj->EventKey:"";
		    $code=isset($postObj->UserCardCode)?$postObj->UserCardCode:"";
		    $OuterId =isset($postObj->OuterId)?$postObj->OuterId:"";
		    $fromUsername=addslashes($fromUsername);
		    $toUsername=addslashes($toUsername);
		    $keyword=addslashes($keyword);
		    $mt=addslashes($mt);
		    $event=addslashes($event);
		    $eventkey=addslashes($eventkey);
		    $code=addslashes($code);
		    $OuterId=addslashes($OuterId);
		    
            include_once BASE_PATH."/model/wxmsg.model.php";
            $msg=new wxmsg();
            if($event=="subscribe"){
                include_once BASE_PATH.'/model/user.model.php';
                $user=new user();
                $user->create_user_for_focus($fromUsername);
            }
            elseif($event=="unsubscribe"){
                include_once BASE_PATH.'/model/user.model.php';
                $user=new user();
                $user->update_user_unfocus_time($fromUsername);
            }
            //领取卡券
            elseif($event=="user_get_card"){
                include_once BASE_PATH."/model/card.model.php";
                $card=new card();
                $card->update_wx_card_use_status($OuterId, 1, $code);
                echo "success";
                exit;
            }
            //核销卡券
            elseif($event=="user_consume_card"){
                include_once BASE_PATH."/model/card.model.php";
                $card=new card();
                $card->update_wx_card_use_status(0, 2, $code);
                echo "success";
                exit;
            }
            $event=str_replace("scan","subscribe", strtolower($event));
            $eventkey=str_replace("qrscene_", "", $eventkey);
            $msg_info_list=$msg->get_answer_trigger_by_type_event($mt,$keyword,$event,$eventkey);
//             
           
            include_once 'access_token.class.php';
            $token=new access_token();
            $access_token=$token->get_token();
            $con="";    
            $url="https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=$access_token";
            
            //msg_type 0表一般信息  1表示关键字信息 2表示事件信息 3表示view信息
            if(is_array($msg_info_list) && !empty($msg_info_list)){
                foreach($msg_info_list as $key=>$msg_info){
                    switch($msg_info['answer_type']){
                        case "card":
                            if($mt=='text'){
                                include_once BASE_PATH."/model/msg.model.php";
                                $msg1=new msg();
                                $msg1->update_user_msg_baseinfo($fromUsername,1,$keyword,'',0);
                                $user_id=$msg1->get_uid_by_open_id($fromUsername);
                                if(!$user_id){
                                    $user_id=0;
                                }
                                $msg_type=1;
                                $msg1->create_msg(1,$user_id,0,$keyword,1,$fromUsername,$msg_type);
                            }
                            elseif($mt=="event"){
                                if($event=="VIEW"){
                                    $msg_type=3;
                                    $user_str="查看网页：".$eventkey;
                                }
                                elseif($event=="subscribe"){
                                    $msg_type=2;
                                    $user_str="关注公众号";
                                }
                                elseif($event=="unsubscribe"){
                                    $msg_type=2;
                                    $user_str="取消关注公众号";
                                }
                                else{
                                    $msg_type=2;
                                    $user_str="其他事件";
                                }
                        
                                include_once BASE_PATH."/model/msg.model.php";
                                $msg1=new msg();
                                $msg1->update_user_msg_baseinfo($fromUsername,1,$user_str,'',0);
                                $user_id=$msg1->get_uid_by_open_id($fromUsername);
                                if(!$user_id){
                                    $user_id=0;
                                }
                                $msg1->create_msg(1,$user_id,0,$user_str,1,$fromUsername,$msg_type);
                            }
                           if($fromUsername=='oHmGrs-r-NoY-QXbtFswtLmbHKY4' || $uid=$this->get_unionid($fromUsername)){
        //                    if($uid="123456"){
                               include_once BASE_PATH.'/model/ext.model.php';
                               $ext=new ext();
                               if($fromUsername=='oHmGrs-r-NoY-QXbtFswtLmbHKY4' ||$ext->is_join($uid, $fromUsername)){
                                    $this->send_card($fromUsername, $msg_info['wx_card_id']);
                                    $data=
                                    '{
                                        "touser":"'.$fromUsername.'",
                                        "msgtype":"text",
                                            "text":
                                            {
                                             "content":"<a href=\'http://dwz.cn/2B4flq\'>主人，点我撒礼包啦。</a>"
                                            }
                                    }';
                                    $ch = curl_init($url);
                                    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                                    curl_setopt($ch, CURLOPT_POST, 1);
                                    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
                                    $data = curl_exec($ch);
                                    $data=json_decode($data,true);
                               }
                           }
                          
                        break;
                        case "news":
                            if($mt=='text'){
                                include_once BASE_PATH."/model/msg.model.php";
                                $msg1=new msg();
                                $msg1->update_user_msg_baseinfo($fromUsername,1,$keyword,'',0);
                                $user_id=$msg1->get_uid_by_open_id($fromUsername);
                                if(!$user_id){
                                    $user_id=0;
                                }
                                $msg_type=1;
                                $msg1->create_msg(1,$user_id,0,$keyword,1,$fromUsername,$msg_type);
                            }
                            elseif($mt=="event"){
                                if($event=="VIEW"){
                                    $msg_type=3;
                                    $user_str="查看网页：".$eventkey;
                                }
                                elseif($event=="subscribe"){
                                    $msg_type=2;
                                    $user_str="关注公众号";
                                }
                                elseif($event=="unsubscribe"){
                                    $msg_type=2;
                                    $user_str="取消关注公众号";
                                }
                                else{
                                    $msg_type=2;
                                    $user_str="其他事件";
                                }
                            
                                include_once BASE_PATH."/model/msg.model.php";
                                $msg1=new msg();
                                 $msg1->update_user_msg_baseinfo($fromUsername,1,$user_str,'',0);
                                $user_id=$msg1->get_uid_by_open_id($fromUsername);
                                if(!$user_id){
                                    $user_id=0;
                                }
                                $msg1->create_msg(1,$user_id,0,$user_str,1,$fromUsername,$msg_type);
                            }
                            $data='
                            {
                                "touser":"'.$fromUsername.'",
                                "msgtype":"news",
                                "news":
                                {
                                  "articles": [
                                     {
                                         "title":"'.$msg_info['answer_title'].'",
                                         "description":"'.$msg_info['answer_desc'].'",
                                         "url":"'.$msg_info['answer_url'].'",
                                         "picurl":"'.SITE_DOMAIN.'/jiaochenhuiAPI/public/img/msg/'.$msg_info['trigger_id'].'.jpg?'.time().'"
                                     }
                                   ]
                                }
                            }';
                            $ch = curl_init($url);
                            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                            curl_setopt($ch, CURLOPT_POST, 1);
                            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
                            $data = curl_exec($ch);
                            $data=json_decode($data,true);
                            break;
                        case "ticket":
                            if($mt=='text'){
                                include_once BASE_PATH."/model/msg.model.php";
                                $msg1=new msg();
                                $msg1->update_user_msg_baseinfo($fromUsername,1,$keyword,'',0);
                                $user_id=$msg1->get_uid_by_open_id($fromUsername);
                                if(!$user_id){
                                    $user_id=0;
                                }
                                $msg_type=1;
                                $msg1->create_msg(1,$user_id,0,$keyword,1,$fromUsername,$msg_type);
                            }
                            elseif($mt=="event"){
                                if($event=="VIEW"){
                                    $msg_type=3;
                                    $user_str="查看网页：".$eventkey;
                                }
                                elseif($event=="subscribe"){
                                    $msg_type=2;
                                    $user_str="关注公众号";
                                }
                                elseif($event=="unsubscribe"){
                                    $msg_type=2;
                                    $user_str="取消关注公众号";
                                }
                                else{
                                    $msg_type=2;
                                    $user_str="其他事件";
                                }
                            
                                include_once BASE_PATH."/model/msg.model.php";
                                $msg1=new msg();
                                 $msg1->update_user_msg_baseinfo($fromUsername,1,$user_str,'',0);
                                $user_id=$msg1->get_uid_by_open_id($fromUsername);
                                if(!$user_id){
                                    $user_id=0;
                                }
                                $msg1->create_msg(1,$user_id,0,$user_str,1,$fromUsername,$msg_type);
                            }
                            if($ticket=$msg->get_user_ticket_by_open_id($msg_info['trigger_id'], $fromUsername, $msg_info['ticket_get_limit'])){
                                if($msg_info['ticket_msg_tem']){
                                    $con=str_replace("{{}}", $ticket, $msg_info['ticket_msg_tem']);
                                }
                                else{
                                    $con=$ticket;
                                }
                                $data='
                                {
                                    "touser":"'.$fromUsername.'",
                                     "msgtype":"text",
                                        "text":
                                        {
                                         "content":"'.$con.'"
                                        }
                                }
                               ';
                            }
                            else{
                                $data='
                                {
                                    "touser":"'.$fromUsername.'",
                                     "msgtype":"text",
                                        "text":
                                        {
                                         "content":"券已被抢光"
                                        }
                                }
                           ';
                            }
                            $ch = curl_init($url);
                            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                            curl_setopt($ch, CURLOPT_POST, 1);
                            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
                            $data = curl_exec($ch);
                            $data=json_decode($data,true);
                            break;
                        
                        case "text":
                            if($mt=='text'){
                                include_once BASE_PATH."/model/msg.model.php";
                                $msg1=new msg();
                                $msg1->update_user_msg_baseinfo($fromUsername,1,$keyword,'',0);
                                $user_id=$msg1->get_uid_by_open_id($fromUsername);
                                if(!$user_id){
                                    $user_id=0;
                                }
                                $msg_type=1;
                                $msg1->create_msg(1,$user_id,0,$keyword,1,$fromUsername,$msg_type);
                            }
                            elseif($mt=="event"){
                                if($event=="VIEW"){
                                    $msg_type=3;
                                    $user_str="查看网页：".$eventkey;
                                }
                                elseif($event=="subscribe"){
                                    $msg_type=2;
                                    $user_str="关注公众号";
                                }
                                elseif($event=="unsubscribe"){
                                    $msg_type=2;
                                    $user_str="取消关注公众号";
                                }
                                else{
                                    $msg_type=2;
                                    $user_str="其他事件";
                                }
                            
                                include_once BASE_PATH."/model/msg.model.php";
                                $msg1=new msg();
                                 $msg1->update_user_msg_baseinfo($fromUsername,1,$user_str,'',0);
                                $user_id=$msg1->get_uid_by_open_id($fromUsername);
                                if(!$user_id){
                                    $user_id=0;
                                }
                                $msg1->create_msg(1,$user_id,0,$user_str,1,$fromUsername,$msg_type);
                            }
                            if($msg_info['answer_url']){
                                $con='<a href=\''.$msg_info['answer_url'].'\'>'.$msg_info['answer_desc'].'</a>';
                            }
                            else{
                                $con=$msg_info['answer_desc'];
                            }
                            $data='
                            {
                                "touser":"'.$fromUsername.'",
                                 "msgtype":"text",
                                    "text":
                                    {
                                     "content":"'.$con.'"
                                    }
                            }
                           ';
                            $ch = curl_init($url);
                            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                            curl_setopt($ch, CURLOPT_POST, 1);
                            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
                            $data = curl_exec($ch);
                            $data=json_decode($data,true);
                            break;
                        default:
                            
                            break;
                    }
            
                }
            }
            else{
                if($mt=='text'){
                    include_once BASE_PATH."/model/msg.model.php";
                    $msg1=new msg();
                    $msg1->update_user_msg_baseinfo($fromUsername,1,$keyword);
                    $user_id=$msg1->get_uid_by_open_id($fromUsername);
                    if(!$user_id){
                        $user_id=0;
                    }
                    $msg_type=0;
                    $msg1->create_msg(1,$user_id,0,$keyword,1,$fromUsername,$msg_type);
                
                    $h=intval(date("H"));
                    $i=intval(date("i"));
                    if(($h<=24 && $h>=20) || ($h<5)){
                        $con="晚上好!
            您的问题，小辰辰将在明早9:00之前尽快给您答复。如事情紧急，请及时联系您的客户经理。
            很晚了，记得早点休息！";
                    }
                    elseif($h>=17 && $h<20){
                        $con="下午好！
            您的问题，小辰辰将在明早9:00之前尽快给您答复。如事情紧急，请及时联系您的客户经理。
            下班高峰期，开车路上请注意安全";
                    }
                    elseif($h>5 && $h<8){
                        $con="早上好！
            您的问题已经收到，小辰辰会尽快给您答复。如事情紧急，请及时联系您的客户经理。
            天气转凉记得加件外套！";
                    }
                    elseif($h==8 && $i<=30){
                        $con="早上好！
            您的问题已经收到，小辰辰会尽快给您答复。如事情紧急，请及时联系您的客户经理。
            天气转凉记得加件外套！";
                    }
                
                    $data='
                                {
                                    "touser":"'.$fromUsername.'",
                                     "msgtype":"text",
                                        "text":
                                        {
                                         "content":"'.$con.'"
                                        }
                                }
                               ';
                    $ch = curl_init($url);
                    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                    curl_setopt($ch, CURLOPT_POST, 1);
                    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
                    $data = curl_exec($ch);
                    $data=json_decode($data,true);
                }
                elseif(in_array($mt, array("image","voice","video","shortvideo"))){
                    include_once BASE_PATH."/model/msg.model.php";
                    $msg1=new msg();
                    $pic_url=isset($postObj->PicUrl)?$postObj->PicUrl:"";
                    $media_id=isset($postObj->MediaId )?$postObj->MediaId:"";
                    switch ($mt){
                        case "image":$msg_type=4;break;
                        case "voice":$msg_type=5;break;
                        case "video":$msg_type=6;break;
                        case "shortvideo":$msg_type=7;break;
                    }
                    $user_id=$msg1->get_uid_by_open_id($fromUsername);
                    if(!$user_id){
                        $user_id=0;
                    }
                    
                    $msg_id=$msg1->create_msg(1,$user_id,0,"",1,$fromUsername,$msg_type);
                    switch ($mt){
                        case "image":
                            $keyword1=addslashes("<img width='100px'  src='".FILE_URL."img/msg_attr/".$msg_id.".attr'/>");
                            break;
                        case "voice":
                            $keyword1="voice_".$msg_id;
                            break;
                        case "shortvideo":
                            $keyword1="shortvideo_".$msg_id;
                            break;
                        case "video":
                            $keyword1="video_".$msg_id;
                            break;
                    }
                    $msg1->update_user_msg_baseinfo($fromUsername,1,$keyword1);
                   
                    $this->get_msg_attr($msg_id, $media_id);
                    
                    $h=intval(date("H"));
                    $i=intval(date("i"));
                    if(($h<=24 && $h>=20) || ($h<5)){
                        $con="晚上好!
            您的问题，小辰辰将在明早9:00之前尽快给您答复。如事情紧急，请及时联系您的客户经理。
            很晚了，记得早点休息！";
                    }
                    elseif($h>=17 && $h<20){
                        $con="下午好！
            您的问题，小辰辰将在明早9:00之前尽快给您答复。如事情紧急，请及时联系您的客户经理。
            下班高峰期，开车路上请注意安全";
                    }
                    elseif($h>5 && $h<8){
                        $con="早上好！
            您的问题已经收到，小辰辰会尽快给您答复。如事情紧急，请及时联系您的客户经理。
            天气转凉记得加件外套！";
                    }
                    elseif($h==8 && $i<=30){
                        $con="早上好！
            您的问题已经收到，小辰辰会尽快给您答复。如事情紧急，请及时联系您的客户经理。
            天气转凉记得加件外套！";
                    }
                    
                    $data='
                                {
                                    "touser":"'.$fromUsername.'",
                                     "msgtype":"text",
                                        "text":
                                        {
                                         "content":"'.$con.'"
                                        }
                                }
                               ';
                    $ch = curl_init($url);
                    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                    curl_setopt($ch, CURLOPT_POST, 1);
                    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
                    $data = curl_exec($ch);
                    $data=json_decode($data,true);
                }
                elseif($mt=="event"){
                
                    if($event=="VIEW"){
                        $user_str="查看网页：".$eventkey;
                        $msg_type=3;
                    }
                    elseif($event=="subscribe"){
                        $user_str="关注公众号";
                        $msg_type=2;
                    }
                    elseif($event=="unsubscribe"){
                
                        $user_str="取消关注公众号";
                        $msg_type=2;
                    }
                    else{
                        $user_str="其他事件";
                        $msg_type=2;
                    }
                    include_once BASE_PATH."/model/msg.model.php";
                    $msg1=new msg();
                    $msg1->update_user_msg_baseinfo($fromUsername,1,$user_str,'',0);
                    $user_id=$msg1->get_uid_by_open_id($fromUsername);
                    if(!$user_id){
                        $user_id=0;
                    }
                    $msg1->create_msg(1,$user_id,0,$user_str,1,$fromUsername,$msg_type);
                
                    if($event=='card_pass_check'|| $event=='card_not_pass_check'){
                        if($event=='card_pass_check'){
                            $status=2;
                        }
                        elseif($event=='card_not_pass_check'){
                            $status=3;
                        }
                        $card_id=isset($postObj->CardId)?$postObj->CardId:"";
                        include_once BASE_PATH.'/model/card.model.php';
                        $card=new card();
                        if($status && $card_id){
                            $card->update_status(addslashes($card_id), $status);
                        }
                    }
                }
            }
            echo "success";
            exit;
		}
		else{
		    echo "success";
		    exit;
		}
    }
    
    function amr2mp3($file){
        
        $s_file= $file;
        $e_file= $file.".mp3";
        system("ffmpeg -i  $s_file $e_file");
    }
    
    function send_ticket($data){
        include_once 'access_token.class.php';
        $token=new access_token();
        $access_token=$token->get_token();
        $con="";
        $url="https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=$access_token";
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        $data = curl_exec($ch);
        $data=json_decode($data,true);
        log::write("send_ticket_return", var_export($data,1));
        if($data['errcode']){
            throw new my_exception("电子券投放失败",SYS_ERROR);
        }
    }
    
    function send_card($open_id,$card_id,$log_id=0){
        include_once 'access_token.class.php';
        $token=new access_token();
        $access_token=$token->get_token();
        $url="https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=$access_token";
        $card_ticket=$token->get_card_token();
        $time=time();
        $nonstr=$this->createNonceStr();
        $code="";
        $tmpArr = array($card_ticket,$time,$card_id,$code,$open_id,$nonstr);
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode( $tmpArr );
        $sign_str = sha1( $tmpStr );
        $data='{
            "touser":"'.$open_id.'",
            "msgtype":"wxcard",
            "wxcard":{ 
            "card_id":"'.$card_id.'",
            "card_ext": 
            "{\"code\":\"'.$code.'\",
            \"openid\":\"'.$open_id.'\",
            \"timestamp\":\"'.$time.'\",
            \"nonce_str\":\"'.$nonstr.'\",
            \"signature\":\"'.$sign_str.'\",
            \"outer_id\":\"'.$log_id.'\"}"
            },
        }';
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        $data = curl_exec($ch);
        $data=json_decode($data,true);
        if($data['errcode']){
            throw new my_exception("卡券投放失败",SYS_ERROR);
        }
    }
		
	private function checkSignature()
	{
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];
		$token = TOKEN;
		$tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr, SORT_STRING);
		$tmpStr = implode( $tmpArr );
		$tmpStr = sha1( $tmpStr );
		
		if( $tmpStr == $signature ){
			return true;
		}else{
			return false;
		}
	}
}

?>